package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.dto.UserDto;
import com.zhentao.mapper.ReviewImageMapper;
import com.zhentao.mapper.UserMapper;
import com.zhentao.pojo.ProductReview;
import com.zhentao.pojo.ReviewImage;
import com.zhentao.pojo.User;
import com.zhentao.service.ProductReviewService;
import com.zhentao.mapper.ProductReviewMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【product_review(商品评价表)】的数据库操作Service实现
* @createDate 2025-08-29 09:27:34
*/
@Service
public class ProductReviewServiceImpl extends ServiceImpl<ProductReviewMapper, ProductReview>
    implements ProductReviewService{

    @Autowired
    private ReviewImageMapper reviewImageMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Page<ProductReview> getProductEvaluation(Integer productId, Integer pageNum, Integer pageSize, Integer sort) {
// 创建分页对象
        Page<ProductReview> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        QueryWrapper<ProductReview> queryWrapper = new QueryWrapper<ProductReview>().eq("product_id", productId);

        // 根据sort参数添加评分筛选条件
        if (sort != null) {
            switch (sort) {
                case 1: // 好评 - 5星
                    queryWrapper.eq("score_star", 5);
                    break;
                case 2: // 中评 - 3-4星
                    queryWrapper.between("score_star", 3, 4);
                    break;
                case 3: // 差评 - 1-2星
                    queryWrapper.between("score_star", 1, 2);
                    break;
                default:
                    // 不按评分条件查询
                    break;
            }
        }

        // 添加默认排序条件
        queryWrapper.orderByDesc("review_time");

        // 执行分页查询
        Page<ProductReview> productReviewPage = this.page(page, queryWrapper);

        List<ProductReview> productReviewList = productReviewPage.getRecords();

        if (!productReviewList.isEmpty()) {
            // 批量获取所有评价的图片，避免N+1查询问题
            List<Long> reviewIds = productReviewList.stream()
                    .map(ProductReview::getReviewId)
                    .toList();

            QueryWrapper<ReviewImage> imageQueryWrapper = new QueryWrapper<ReviewImage>()
                    .in("review_id", reviewIds);
            List<ReviewImage> allReviewImages = reviewImageMapper.selectList(imageQueryWrapper);

            // 将图片按reviewId分组
            Map<Long, List<ReviewImage>> imageMap = allReviewImages.stream()
                    .collect(Collectors.groupingBy(ReviewImage::getReviewId));

            // 批量获取所有评价的用户信息，避免N+1查询问题
            List<Long> userIds = productReviewList.stream()
                    .map(ProductReview::getUserId)
                    .filter(userId -> userId != null)
                    .toList();

            Map<Long, User> userMap = new HashMap<>();
            if (!userIds.isEmpty()) {
                List<User> allUsers = userMapper.selectBatchIds(userIds);
                userMap = allUsers.stream()
                        .collect(Collectors.toMap(User::getId, user -> user));
            }

            // 设置每个评价的图片列表和用户信息
            for (ProductReview productReview : productReviewList) {
                List<ReviewImage> images = imageMap.getOrDefault(productReview.getReviewId(), List.of());
                productReview.setReviewImages(images);

                User user = userMap.get(productReview.getUserId());
                if (user != null) {
                    UserDto userDto = new UserDto();
                    userDto.setNickName(user.getNickname());
                    userDto.setAvatar(user.getAvatar());
                    productReview.setUser(userDto);
                } else {
                    productReview.setUser(null);
                }
            }
        }

        return productReviewPage;
    }
}




